﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace AutoSort
{
    class Configuration
    {
        private static Logger log = Logger.getLogger(typeof(Configuration));

        public string InputFolder { get; set; }
        public string OutputFolder { get; set; }
        public List<Item> Items { get; set; }

        public Configuration()
        {
            /* Assign default values */
            InputFolder = @"C:\Projekter\AutoSort\Input";
            OutputFolder = @"C:\Projekter\AutoSort\Output";
            Items = new List<Item>();
            //Items.Add(new Item(".*Super.*Man.*", "Superman"));
            //Items.Add(new Item(".*Spider.*Man.*", "Spiderman"));
            /* Attempt to load from Configuration file */
            LoadConfiguration();
        }

        private void LoadConfiguration()
        {
            try
            {
                /* try to load Configuration.xml from the current folder */
                FileInfo configFile = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + @"\" + "config.xml");
                if (configFile.Exists)
                {
                    XmlDocument configXml = new XmlDocument();
                    configXml.Load(new XmlTextReader(configFile.FullName));

                    XmlNode inputFolderNode = configXml.SelectSingleNode("//Configuration/Inputfolder");
                    InputFolder = inputFolderNode.InnerText;

                    XmlNode outputFolderNode = configXml.SelectSingleNode("//Configuration/Outputfolder");
                    OutputFolder = outputFolderNode.InnerText;

                    XmlNodeList itemNodes = configXml.SelectNodes("//Configuration/Items/Item");
                    foreach (XmlNode item in itemNodes)
                    {
                        string pattern = item.SelectSingleNode("//Pattern").InnerText;
                        string folder = item.SelectSingleNode("//Folder").InnerText;
                        Items.Add(new Item(pattern, folder));
                    }
                }
            }
            catch (Exception e)
            {
                log.Error("Exception while loading configuration", e);
            }



            /* 
             Not implemented yet.
             */
        }

        
    }
}
